package com.snb.play.dwebtoon.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

import com.snb.play.dwebtoon.IntroActivity;
import com.snb.play.dwebtoon.data.DTO_WebToon;

public class DownloadService extends Service {

	public class DownLoaderBinder extends Binder {

		public DownloadService getService() {
			Logger.d(TAG, "getService() DownLoaderBinder");
			return DownloadService.this;
		}
	}

	public enum GINFO_STATUS {
		IDLE, SAVE
	}

	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			// showNotification("다운로드를 시작합니다.", "VVS");
			// stopSelf(msg.arg1);
		}
	}

	public enum WEBTOON_SELECT_TYPE {
		TOON_ALL, TOON_BY_ARTIST, TOON_BY_DAY, TOON_BY_TITLE, TOON_FINISHED, TOON_NONE, TOON_SAVED, TOON_SCORE
	}

	public static final String FULLDIRSIZE = "FULL_DIR_SIZE";

	public static Context mContext;

	public static boolean serviceState = false;

	private static final String SNB_WEBTOON = "SNB_WEBTOON";

	public static String TAG = DownloadService.class.getSimpleName();

	public ArrayList<DTO_WebToon> gInfo;

	private RESTFulClient gRestFulClient;

	private final IBinder mBinder = new DownLoaderBinder();

	private Map<String, ToonLoaderTask> mDownLoders;

	private DTO_WebToon mDto_WebToon;

	private NotificationManager mNM;

	private WEBTOON_SELECT_TYPE mSelect_TYPE = WEBTOON_SELECT_TYPE.TOON_NONE;

	private ServiceHandler mServiceHandler;

	private Looper mServiceLooper;

	public GINFO_STATUS mStatus;

//	public void addFileSize(long aFileSize) {
//		getEditor(getApplicationContext()).putLong(FULLDIRSIZE, getSharedPref(getApplicationContext()).getLong(FULLDIRSIZE, 0) + aFileSize).commit();
//	}

//	public void deleteFileSize(long aFileSize) {
//		getEditor(getApplicationContext()).putLong(FULLDIRSIZE, getSharedPref(getApplicationContext()).getLong(FULLDIRSIZE, 0) - aFileSize).commit();
//	}

	public void finishToonLoaderTask(final String aKey) {
		synchronized (mDownLoders) {
			if (mDownLoders.containsKey(aKey)) {
				Intent intent = new Intent("snb.comic.downComplete");
				intent.putExtra("TITLE", mDownLoders.get(aKey).mWebToon.mToonName);
				sendBroadcast(intent);

				mDownLoders.get(aKey).calledStop();
				mDownLoders.remove(aKey);
			}

			Logger.d(TAG, "mDownLoders.size() ==" + mDownLoders.size());
			if (mDownLoders.size() > 0 && mDownLoders.keySet().iterator().hasNext()) {
				String lKey = mDownLoders.keySet().iterator().next();
				if (mDownLoders.containsKey(lKey))
					mDownLoders.get(lKey).doInBackground(lKey);
			}
		}

		IntroActivity.gCheckedSize = false;
		SharedPreferences.Editor lEditor = getSharedPref(mContext.getApplicationContext()).edit();
		lEditor.putBoolean("gCheckedSize", IntroActivity.gCheckedSize);
		lEditor.commit();
	}

	public int getCurrentGInfoSize() {
		if (gInfo == null)
			return 0;
		return gInfo.size();
	}

	public Editor getEditor(Context aContext) {
		return getSharedPref(aContext).edit();
	}

	public long getFullDirSize(Context aContext) {
		return getSharedPref(aContext).getLong(FULLDIRSIZE, 0);
	}

	public synchronized ArrayList<DTO_WebToon> getGInfo(WEBTOON_SELECT_TYPE aSelect_TYPE, DTO_WebToon aDto_WebToon, int minScore) {
		boolean isAnd = true;
		boolean doGet = false;

		if ((gInfo == null || gInfo.isEmpty() || gInfo.size() < 1) && mStatus == GINFO_STATUS.IDLE)
			doGet = true;
		else if (!this.mSelect_TYPE.equals(aSelect_TYPE))
			doGet = true;
		else if (this.mDto_WebToon == null)
			doGet = true;
		else {
			doGet = true;

			if (this.mDto_WebToon.picture_artists != null && this.mDto_WebToon.picture_artists.length() > 0
					&& this.mDto_WebToon.picture_artists.equalsIgnoreCase(aDto_WebToon.picture_artists))
				doGet = false;
			else if (this.mDto_WebToon.write_artists != null && this.mDto_WebToon.write_artists.length() > 0
					&& this.mDto_WebToon.write_artists.equalsIgnoreCase(aDto_WebToon.write_artists))
				doGet = false;
			else if (this.mDto_WebToon.title != null && this.mDto_WebToon.title.length() > 0
					&& this.mDto_WebToon.title.equalsIgnoreCase(aDto_WebToon.title))
				doGet = false;
			else if (this.mDto_WebToon.savedYn != null && this.mDto_WebToon.savedYn.length() > 0
					&& this.mDto_WebToon.savedYn.equalsIgnoreCase(aDto_WebToon.savedYn))
				doGet = false;
			else if (this.mDto_WebToon.webtoonWeeks != null && this.mDto_WebToon.webtoonWeeks.length() > 0
					&& this.mDto_WebToon.webtoonWeeks.equalsIgnoreCase(aDto_WebToon.webtoonWeeks))
				doGet = false;
			else if ((this.mDto_WebToon.webtoonWeeks == null || this.mDto_WebToon.webtoonWeeks.length() == 0)
					|| (this.mDto_WebToon.savedYn == null || this.mDto_WebToon.savedYn.length() == 0)
					|| (this.mDto_WebToon.title == null || this.mDto_WebToon.title.length() == 0)
					|| (this.mDto_WebToon.write_artists == null || this.mDto_WebToon.write_artists.length() == 0)
					|| (this.mDto_WebToon.picture_artists == null || this.mDto_WebToon.picture_artists.length() == 0))
				doGet = false;

			if (aSelect_TYPE == WEBTOON_SELECT_TYPE.TOON_BY_DAY) {
				if (this.mDto_WebToon.webtoonWeeks.equalsIgnoreCase(aDto_WebToon.webtoonWeeks))
					doGet = true;
			}
		}

		if (doGet) {
			switch (aSelect_TYPE) {
				case TOON_ALL:
					break;
				case TOON_BY_ARTIST:
					isAnd = false;
					break;
				case TOON_BY_DAY:
					break;
				case TOON_BY_TITLE:
					break;
				case TOON_FINISHED:
					break;
				case TOON_SCORE:
					break;
				default:
					break;
			}
			
			this.gInfo = DBProvider.getInstance().getToons(aDto_WebToon, isAnd);
			if (this.gInfo != null && this.gInfo.size() > 0) {
				for (DTO_WebToon lDto_WebToon : this.gInfo)
					if (lDto_WebToon.score.trim().length() > 0 && aDto_WebToon.score.trim().length() > 0 )
						if ((Float.valueOf(lDto_WebToon.score) > Float.valueOf(aDto_WebToon.score)) || (Float.valueOf(lDto_WebToon.score) < minScore)) {
							this.gInfo.remove(lDto_WebToon);
						}
			}
		}

		if (this.gInfo == null) {
			this.gInfo = new ArrayList<DTO_WebToon>();
		}

		this.mSelect_TYPE = aSelect_TYPE;
		this.mDto_WebToon = aDto_WebToon;

		return this.gInfo;

	}

	public synchronized int getGInfoSize() {
		return DBProvider.getInstance().getObjTotalSize(DTO_WebToon.class);
	}

	public synchronized RESTFulClient getRest() {

		if (gRestFulClient == null)
			gRestFulClient = new RESTFulClient();
		synchronized (gRestFulClient) {
			return gRestFulClient;
		}
	}

	public SharedPreferences getSharedPref(Context aContext) {
		return aContext.getSharedPreferences(SNB_WEBTOON, Activity.MODE_PRIVATE);
	}

	public boolean haveToonLoaderTsk(String aKey) {
		return mDownLoders.containsKey(aKey);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// We don't provide binding, so return null
		return mBinder;
	}

	@Override
	public void onCreate() {
		serviceState = true;
		if (mDownLoders == null)
			mDownLoders = new HashMap<String, ToonLoaderTask>();

		mContext = getApplication().getApplicationContext();
		Logger.d(TAG, "onCreate() DownloadService");
		mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		HandlerThread thread = new HandlerThread("ServiceStartArguments", 1);
		thread.start();
		// Get the HandlerThread's Looper and use it for our Handler
		mServiceLooper = thread.getLooper();
		mServiceHandler = new ServiceHandler(mServiceLooper);

	}

	@Override
	public void onDestroy() {
		Logger.d("SERVICE-DESTROY", "DESTORY");
		serviceState = false;
		// Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Logger.d("SERVICE-ONCOMMAND", "onStartCommand");
		Bundle extra = intent.getExtras();
		if (extra != null) {
			// String downloadUrl = extra.getString("downloadUrl");
			// Logger.d("URL", downloadUrl);
			//
			// this.downloadUrl = downloadUrl;
		}

		// Message msg = mServiceHandler.obtainMessage();
		// msg.arg1 = startId;
		// mServiceHandler.sendMessage(msg);

		// If we get killed, after returning from here, restart
		return START_STICKY;
	}

	public synchronized ArrayList<DTO_WebToon> putGInfo(DTO_WebToon aDto_WebToon) {
		boolean isHave = false;
		for (DTO_WebToon lDto_WebToon : gInfo) {
			if (lDto_WebToon.getId().trim().equalsIgnoreCase(aDto_WebToon.getId().trim())) {
				isHave = true;
				break;
			}
		}
		if (!isHave)
			gInfo.add(aDto_WebToon);
		return gInfo;

	}

	public synchronized void resetGInfofilter() {
		this.mSelect_TYPE = WEBTOON_SELECT_TYPE.TOON_NONE;
		this.mDto_WebToon = null;
	}

	public void setToonLoaderTask(final String aKey, SharedData aWebToon) {
		synchronized (mDownLoders) {
			if (!mDownLoders.containsKey(aKey)) {
				mDownLoders.put(aKey, new ToonLoaderTask(this, aWebToon));
				Logger.d(TAG, "mDownLoders.size() ==" + mDownLoders.size());
				if (mDownLoders.size() == 1) {
					mDownLoders.get(aKey).doInBackground(aKey);
				}
			}
		}

	}
	//
	// void showNotification(String message, String title) {
	// // In this sample, we'll use the same text for the ticker and the
	// // expanded notification
	// CharSequence text = message;
	//
	// // Set the icon, scrolling text and timestamp
	// Notification notification = new Notification(R.drawable.snb_comic_icon,
	// "vvs", System.currentTimeMillis());
	// notification.flags |= Notification.FLAG_AUTO_CANCEL;
	// Intent intent = new Intent(this, WebToonListActivity.class);
	// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// // The PendingIntent to launch our activity if the user selects this
	// // notification
	// PendingIntent contentIntent =
	// PendingIntent.getActivity(this.getBaseContext(), 0, intent,
	// PendingIntent.FLAG_CANCEL_CURRENT);
	//
	// // Set the info for the views that show in the notification panel.
	// notification.setLatestEventInfo(this, title, text, contentIntent);
	// // Send the notification.
	// // We use a layout id because it is a unique number. We use it later to
	// // cancel.
	// mNM.notify(R.string.app_name, notification);
	//
	// }
}